package com.hzbank.aaronkotlin

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.PixelCopy
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.hzbank.aaronkotlin.databinding.ActivityHomeBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.time.delay
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.time.Duration
import java.time.temporal.TemporalUnit
import java.util.concurrent.TimeUnit

class MainActivity : BaseActivity<ActivityHomeBinding>() {

    //创建 viewmodel
    private val viewModel: BaseViewModel by viewModels<BaseViewModel>()

    private val handlerThread: HandlerThread by lazy {

        HandlerThread("IoThread")
    }

    private val blueHelper: BlueHelper by lazy {

        BlueHelper.getInstance(this@MainActivity)
    }

    override fun getBinding() =
        ActivityHomeBinding.inflate(LayoutInflater.from(this))

    override fun parseView() {

//        requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
//            android.Manifest.permission.READ_EXTERNAL_STORAGE,
//            android.Manifest.permission.READ_CONTACTS)

        xBing?.showTips?.setText("Hello, AaronKotlin")

        xBing?.operator01?.setOnClickListener{

            it.toast("执行协程")
            xBing?.operator01?.showLoading(LoadingDialog.getInstance(this), true)

            viewModel.doOperator01()

        }

        xBing?.operator02?.setOnClickListener {

            it.toast("接口请求中")
            xBing?.operator02?.showLoading(LoadingDialog.getInstance(this), true)

            val params = JsonObject();
            params.addProperty("name", "杭州市")

            viewModel.doOperator02("api/weather", params)

        }

        xBing?.operator03?.setOnClickListener {

            lifecycleScope.launch(Dispatchers.Default){

                val secretKey = JniHelper.getSecretKey()

                withContext(Dispatchers.Main){

                    xBing?.showTips?.setText("jni 获取密钥="+secretKey)

                }

            }

        }

        xBing?.operator04?.setOnClickListener {

            //跳转到画板
            startActivity(Intent(this@MainActivity, ArtBoardActivity::class.java))

        }

        xBing?.operator05?.setOnClickListener {

            //跳转到画板
            startActivity(Intent(this@MainActivity, DocumentPrewActivity::class.java))

        }

        xBing?.operator06?.setOnClickListener {

            lifecycleScope.launch(Dispatchers.IO) {

                //截图
                val rootView = this@MainActivity.window.decorView.rootView
                val bitmap = Bitmap.createBitmap(rootView.width, rootView.height, Bitmap.Config.ARGB_8888)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    PixelCopy.request(
                        this@MainActivity.window,
                        Rect(0, 0, rootView.width, rootView.height),
                        bitmap, {

                            if(it == PixelCopy.SUCCESS){

                                //截图成功

                                "截图成功".toast(this@MainActivity)

                                xBing?.operator07?.setImageBitmap(bitmap)

                            } else{

                                //截图失败
                                "截图失败".toast(this@MainActivity)

                            }
                        },
                        Handler(Looper.getMainLooper())
                    )
                } else{

                    //低版本

                }

            }

        }

        xBing?.operator08?.setOnClickListener {

            handlerThread?.start()

            val hadler = Handler(handlerThread?.looper!!){

                when(it.what){

                    1 -> {

                        "handlerThread接收消息-线程=${Thread.currentThread().name}".toast(this@MainActivity)

                        handlerThread?.quitSafely()
                        true
                    }

                    2 -> {

                        true
                    }

                    else -> false



                }

            }

            val msg = Message.obtain()
            msg.what = 1

            hadler.sendMessage(msg)

        }

        xBing?.operator09?.setOnClickListener {


            requestPermission({

                    if(blueHelper.blueEnabled()){

                        blueHelper.scanBlue({ callbackType, result ->


                        }, {errorCode ->


                        })

                    } else{

                        "蓝牙不可用，请手动打开".toast(this@MainActivity)
                    }

                }, {

                    val builder: StringBuilder = StringBuilder()
                    it.forEach{
                        builder.append(it)
                    }
                (builder.toString()+"，仍未获取权限").toast(this@MainActivity)

            }, android.Manifest.permission.BLUETOOTH,
                android.Manifest.permission.BLUETOOTH_SCAN,)

        }

        lifecycleScope.launch(Dispatchers.Main) {

            viewModel.stateApiFlow.collect{

                it?.let {

                    if(!TextUtils.isEmpty(it.code)){

                        if(TextUtils.equals("200", it.code)){

                            xBing?.showTips?.setText(Gson().toJson(it))

                            xBing?.operator02?.toast("获取天气成功")


                        }else{

                            xBing?.operator02?.toast("获取天气失败"+it.msg)
                        }

                    }


                }

                xBing?.operator02?.showLoading(LoadingDialog.getInstance(this@MainActivity), false)

            }

        }

        lifecycleScope.launch(Dispatchers.Main){

            viewModel.stateFlow.collect{

                ("viewModel数据收集="+it).showLog()
                if(!TextUtils.isEmpty(it)){


                    xBing?.showTips?.setText(it)

                    xBing?.operator01?.showLoading(LoadingDialog.getInstance(this@MainActivity), false)
                }
            }

        }

        val imageShow: KdbImgShowView = KdbImgShowView(this@MainActivity)

        imageShow.addCallback(object : KdbImgShowView.KdbImgShowCallback{
            override fun closeBigPic() {

            }
        })

        //保存 pdf 到本地文件
        lifecycleScope.launch (Dispatchers.IO){


            val pdfDir = File(DocumentPrewActivity.docFilePath);
            if(null == pdfDir || !pdfDir.exists()){

                pdfDir.mkdirs();

            }

            var inputStream: InputStream? = null
            var outputStream: FileOutputStream? = null
            try {
                inputStream = this@MainActivity.assets.open("test.pdf")
                val destinationFile = File(DocumentPrewActivity.docFilePath+"test.pdf")
                outputStream = FileOutputStream(destinationFile)

                val buffer = ByteArray(1024)
                var length: Int
                while (inputStream.read(buffer).also { length = it } > 0) {
                    outputStream.write(buffer, 0, length)
                }

                outputStream.flush()
            } catch (e: IOException) {
                e.printStackTrace()
            } finally {

                outputStream?.close()
                inputStream?.close()
            }


        }
    }

    override fun onDestroy() {
        handlerThread?.quitSafely()
        super.onDestroy()
    }
}